const api = require('../../../../utils/utils')

Page({
  data: {
    user: {
      password: "",
      password_new: "",
      confirm: ""
    },
    passwordRules: [{
      required: true,
      message: '请输入旧密码',
      trigger: 'blur'
    }],
    passwordnewRules: [{
        required: true,
        message: '请输入新密码',
        trigger: 'blur'
      },
      {
        min: 8,
        max: 16,
        message: '密码长度在8-16个字符之间',
        trigger: 'blur'
      },
      {
        pattern: '^[A-Za-z0-9]+$',
        message: '密码必须由数字字母组成',
        trigger: 'blur'
      }
    ],
    confirmRules: [{
        required: true,
        message: '请确认密码',
        trigger: 'blur'
      },
      {
        validator(rule, value, callback, source) {
          const {
            password_new,
            confirm
          } = source;
          if (password_new !== confirm) {
            callback(false);
          }
          callback()
        },
        message: '两次密码输入不一致',
        trigger: 'change'
      }
    ],
  },
  onLoad: function (options) {
    // 初始化表单信息
    wx.lin.initValidateForm(this)
    // 设置当前导航栏标题
    wx.setNavigationBarTitle({
      title: '修改密码'
    })
  },
  submit(event) {
    const detail = event.detail
    const toast = this.selectComponent("#mytoast")
    if (detail.isValidate === false) {
      toast.linShow({
        title:"输入格式错误！",
        icon:"error"
      })
      return
    }
    this.send_updatepwd(detail.values)
  },
  send_updatepwd(formData) {
    const data = {
      "old_password": formData.password,
      "password": formData.password_new,
      "password2": formData.confirm
    }
    const toast = this.selectComponent("#mytoast")
    api.request('put', "/passwords/pwd/", data)
      .then((res) => {
        toast.linShow({
          title:"修改成功！",
          icon:"success"
        })
        // 注册成功后定时返回
        setTimeout(() => {
          wx.navigateBack({
            delta: 1,
          })
        }, 1000)
      })
      .catch((err) => {
        toast.linShow({
          title:"旧密码错误",
          icon:"error"
        })
      })
  }
})